﻿@{
    ViewBag.Title = "Maps JavaScript API";
}

<div id="map_canvas" style="width:100%; height:100%"></div>

<div id="map_controls" class="gm-style-mtc" style="float: left;">
    <div class="map_control top_center" title="搜索" onclick="Search.Toggle()">
        搜索
        <div class="dropdown" style="width: 300px;">
            <input type="text" id="iptSearch" placeholder="Search" style="width: 240px;" />
            <button onclick="Search.Search()" style="width: 50px;">搜索</button>
        </div>
    </div>
    <div class="map_control top_center" title="维护楼盘" onclick="Building.Add()">楼盘</div>
</div>

<div id="buildingInfo" class="easyui-window" title="楼盘详情" 
    data-options="
        modal:true,
        closed:true,
        iconCls:'icon-save'" 
    style="width:500px;height:200px;padding:10px;">
    The window content.
</div>
<div id="map_menu" class="easyui-menu" style="width: 120px;">
    <div onclick="">标记楼盘</div>
    <div class="menu-sep"></div>
    <div>Exit</div>
</div>

@section CascadingStyleSheets {
    <style type="text/css">
        html { height: 100% }
        body {height: 100%;margin: 0;padding: 0 }
        #map_canvas { height: 100% }

        .map_control, .dropdown {
            direction: ltr;
            text-align: center;
            position: relative;
            color: rgb(86, 86, 86);
            font-family: Roboto, Arial, sans-serif;
            -webkit-user-select: none;
            font-size: 11px;
            background-color: rgb(255, 255, 255);
            padding: 1px 6px;
            border-bottom-left-radius: 2px;
            border-top-left-radius: 2px;
            -webkit-background-clip: padding-box;
            background-clip: padding-box;
            border: 1px solid rgba(0, 0, 0, 0.14902);
            -webkit-box-shadow: rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px;
            box-shadow: rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px;
            min-width: 26px;
            font-weight: 500;

            cursor: pointer;
            float: left;
        }
        .map_control:hover {
            color: rgb(0, 0, 0);
            background-color: rgb(235, 235, 235);
        }

        .map_control .dropdown {
            display: none;
            position: absolute;
            top: 20px;
            left: 0;
        }

        .top_center {
            margin-top: 5px;
        }
    </style>
}
@section Javascript {
    <script type="text/javascript">
        var MapAPI = function(name, dom, options) {
            var geocoder, map;
            var _opt = $.extend({
                address: '中国',
                zoom: MapAPI.ZoomDic.country
            }, options);
            var _markerArray = [];
            var _cache = {
                LatLng: {}
            };

            //ctor
            (function() {
                if (MapAPI.NowIs == 'google') {
                    $.ajax({
                        url: '//maps.googleapis.com/maps/api/js',
                        data: {
                            key: 'AIzaSyDTmbPavjFLTLZktNs0RR19pt662lAa1Gk',
                            sensor: false,
                            callback: name + '.Initialize'
                        },
                        type: 'GET',
                        async: true,
                        dataType: "script",
                        context: document.body,
                        crossDomain: true,
                        cache: true
                    }).then(function() {
                        MapAPI.NowIs = 'google*';
                    }).fail(function(jqxhr, settings, exception) {
                        MapAPI.NowIs = 'baidu';
                    });
                };
                if (MapAPI.NowIs == 'baidu') {
                };
            })();

            var _changeToLatLng = function(value, fn) {
                if (typeof value === "string") {
                    //字符串，地址查询后处理
                    if (!_cache.LatLng[value]) {
                        geocoder.geocode({ 'address': value }, function (results, status) {
                            if (status == google.maps.GeocoderStatus.OK) {
                                console.info(results);

                                _cache.LatLng[value] = {
                                    latlng: results[0].geometry.location,
                                    type: results[0].types[0]
                                };
                                fn(_cache.LatLng[value].latlng, _cache.LatLng[value].type);
                            } else {
                                throw new Error("Geocode was not successful for the following reason: " + status);
                            }
                        });
                    } else {
                        fn(_cache.LatLng[value].latlng, _cache.LatLng[value].type);
                    }
                } else if (Array.isArray(value) && value.length === 2 && !isNaN(value[0]) && !isNaN(value[1])) {
                    //数组，[北纬, 东经]
                    fn(new google.maps.LatLng(value[0], value[1]));
                } else if (!!value.lat && !!value.lng) {
                    if (typeof value.lat === "function" && typeof value.lng === "function") {
                        //LatLng对象
                        fn(value);
                    } else if (!isNaN(value.lat) && !isNaN(value.lng)) {
                        //JSON，{ lat: 北纬, lng: 东经 }
                        fn(new google.maps.LatLng(value.lat, value.lng));
                    }
                }
            };

            this.Initialize = function() {
                var mapOptions = {
                    center: new google.maps.LatLng(35.862, 104.195),
                    zoom: MapAPI.ZoomDic.country,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                geocoder = new google.maps.Geocoder();
                map = new google.maps.Map(dom, mapOptions);

                if ($('#map_controls').size() > 0) {
                    map.controls[google.maps.ControlPosition.TOP_CENTER].push($('#map_controls')[0]);
                }
            };

            this.SetLocation = function(latLng) {
                _changeToLatLng(latLng, function (latLng, type) {
                    map.setCenter(latLng);
                    map.setZoom(MapAPI.ZoomDic[type] || 10);
                });
            };

            this.AddMarker = function(latLng) {
                _changeToLatLng(latLng, function(latLng) {
                    var marker = new google.maps.Marker({
                        map: map,
                        position: latLng
                    });
                    _markerArray.push(marker);
                    marker.setMap(map);
                });
            };

            this.RemoveMarker = function(latLng) {
                _changeToLatLng(latLng, function(latLng) {
                    for (var i in _markerArray) {
                        if (_markerArray[i].position.equals(latLng)) {
                            _markerArray[i].setMap(null);
                            _markerArray.splice(i, 1);
                            break;
                        }
                    }
                });
            };

            this.AddEvent = function (dom, eventType, fn) {
                if (arguments.length == 2) {
                    fn = eventType;
                    eventType = dom;
                    dom = null;
                }
                google.maps.event.addDomListener(dom || map, eventType, fn);
            }

            this.AddControl = function (dom) {
                map.controls[google.maps.ControlPosition.TOP_CENTER].push(dom);
            }
        };
        //定义缩放级别
        MapAPI.ZoomDic = {
            "country": 4,
            "political": 8,
            "administrative_area_level_1": 8,
            "locality": 12,
            "route": 16,
            "point_of_interest": 18
        };
        MapAPI.NowIs = 'google';
        MapAPI.Create = function(name, dom, options) {
            if (window[name]) {
                throw new Error(name + ' is exists!');
            };
            window[name] = new MapAPI(name, dom, options);
        };

        MapAPI.Create('api', $("#map_canvas")[0]);
        $(window).load(function() {
            api.SetLocation('武汉');
            api.AddEvent('mousedown', function () {
                //鼠标右键
                if (event.which == 3) {
                    $('#map_menu').menu('show', {
                        left: event.pageX,
                        top: event.pageY
                    });
                }
            });
        });

        var Building = (function () {
            var _arrBuilding = [];

            return {
                Add: function () {
                    $('#buildingInfo').window('open');
                }
            }
        })();

        var Search = (function () {
            return {
                Toggle: function () {
                    $(event.target).find('.dropdown').slideToggle();
                },
                Search: function () {
                    api.SetLocation($('#iptSearch').val());
                    api.AddMarker($('#iptSearch').val());
                }
            }
        })();
    </script>
}